import { defineComponent, computed, reactive, toRefs, onMounted, watch, nextTick, watchEffect } from "vue"
import { inject } from "vue"
import { 是浏览器环境否 } from "amtf/utils"

import {
    isLastColumnByColKey,
    isLastRowByRowKey,
    getColKeysByRangeColKeys,
    isExistGivenFixedColKey,
    isExistNotFixedColKey,
    getLeftmostColKey,
    getRightmostColKey,
    getColKeysByFixedTypeWithinColKeys,
    getTotalWidthByColKeys,
    getPreviewColKey,
    getNextColKey,
} from "../util"
import {
    EMIT_EVENTS,
    HOOKS_NAME,
    AUTOFILLING_DIRECTION,
    CURRENT_CELL_SELECTION_TYPES,
    COLUMN_FIXED_TYPE,
} from "../util/constant"
import { INSTANCE_METHODS } from "./constant"
// import { debounce } from 'lodash'
import { useDebounceFn } from "@vueuse/core"

import emitter from "amtf/utils/emitter"
import { useEmitter } from "amtf/hooks"

import { use样式 } from "amtf/hooks"
import { isEmptyValue, getValByUnit, 拼组件名, isFunction, isBoolean, getRandomId } from "amtf/utils"
const 主名 = "table-selection"
const 组件名 = 拼组件名(主名)

export default defineComponent({
    name: 组件名,
    props: {
        父级a: {
            type: Object,
            default: null,
        },
        tableEl: {
            type: 是浏览器环境否 ? HTMLTableElement : Object,
            default: null,
        },
        allRowKeys: {
            type: Array,
            required: true,
        },
        colgroups: {
            type: Array,
            required: true,
        },
        parentRendered: {
            type: Boolean,
            required: true,
        },
        hooks: {
            type: Object,
            required: true,
        },
        // cell autofill option
        cellAutofillOption: {
            type: [Object, Boolean],
            default: () => null,
        },
        cellSelectionData: {
            type: Object,
            required: true,
        },
        cellSelectionRangeData: {
            type: Object,
            required: true,
        },
        isAutofillStarting: {
            type: Boolean,
            required: true,
        },
        currentCellSelectionType: {
            type: String,
            default: "",
        },
        // is scrolling
        showVirtualScrollingPlaceholder: {
            type: Boolean,
            default: false,
        },
        isVirtualScroll: {
            type: Boolean,
            default: false,
        },
        virtualScrollVisibleIndexs: {
            type: Object,
            required: true,
        },
        isCellEditing: {
            type: Boolean,
            default: false,
        },
    },
    setup(props) {
        // console.log(`props 👉`, props)
        const { dispatch } = useEmitter(inject("表格id"))
        const { 拼样式名_table直属 } = use样式(主名)

        const a = reactive({
            currentCellEl: null,
            normalEndCellEl: null,
            autoFillEndCellEl: null,
            cellSelectionRect: {
                currentCellRect: {
                    left: 0,
                    top: 0,
                    width: 0,
                    height: 0,
                },
                normalEndCellRect: {
                    left: 0,
                    top: 0,
                    width: 0,
                    height: 0,
                },
                autoFillEndCellRect: {
                    left: 0,
                    top: 0,
                    width: 0,
                    height: 0,
                },
            },
        })

        const selectionBordersVisibility = computed(() => {
            // console.log(`selectionBordersVisibility ing👇`)
            let result = true
            if (props.isVirtualScroll) {
                const {
                    showVirtualScrollingPlaceholder,
                    cellSelectionData,
                    virtualScrollVisibleIndexs,
                    currentCellSelectionType,
                } = props

                if (showVirtualScrollingPlaceholder) {
                    result = false
                } else {
                    const { currentCell, normalEndCell } = cellSelectionData

                    if (currentCellSelectionType === CURRENT_CELL_SELECTION_TYPES.SINGLE) {
                        if (
                            currentCell.rowIndex < virtualScrollVisibleIndexs.start ||
                            currentCell.rowIndex > virtualScrollVisibleIndexs.end
                        ) {
                            result = false
                        }
                    }

                    if (currentCellSelectionType === CURRENT_CELL_SELECTION_TYPES.RANGE) {
                        if (
                            (currentCell.rowIndex < virtualScrollVisibleIndexs.start &&
                                normalEndCell.rowIndex < virtualScrollVisibleIndexs.start) ||
                            (currentCell.rowIndex > virtualScrollVisibleIndexs.end &&
                                normalEndCell.rowIndex > virtualScrollVisibleIndexs.end)
                        ) {
                            result = false
                        }
                    }
                }
            }
            return result
        })

        const showCorner = computed(() => {
            let result = true
            const { cellAutofillOption } = props
            if (cellAutofillOption) {
                const { directionX, directionY } = cellAutofillOption
                if (isBoolean(directionY) && !directionY && isBoolean(directionX) && !directionX) {
                    result = false
                }
            } else {
                result = false
            }

            return result
        })

        const cornerCellInfo = computed(() => {
            const { allRowKeys, colgroups, cellSelectionRangeData } = props

            const { rightColKey, bottomRowKey } = cellSelectionRangeData

            let isLastColumn = false
            if (isLastColumnByColKey(rightColKey, colgroups)) {
                isLastColumn = true
            } else {
                const index = colgroups.findIndex(x => x.key === rightColKey)
                // right col is right fixed and current col is not right fixed
                if (
                    colgroups[index + 1].fixed === COLUMN_FIXED_TYPE.RIGHT &&
                    colgroups[index].fixed !== COLUMN_FIXED_TYPE.RIGHT
                ) {
                    isLastColumn = true
                }
            }

            let isLastRow = false
            if (isLastRowByRowKey(bottomRowKey, allRowKeys)) {
                isLastRow = true
            }

            return {
                isLastColumn,
                isLastRow,
            }
        })

        const isFirstSelectionRow = computed(() => {
            const { allRowKeys, cellSelectionRangeData } = props
            return allRowKeys[0] === cellSelectionRangeData.topRowKey
        })

        const isFirstSelectionCol = computed(() => {
            const { colgroups, cellSelectionRangeData } = props
            return colgroups[0].key === cellSelectionRangeData.leftColKey
        })

        const isFirstNotFixedSelectionCol = computed(() => {
            let result = false

            const { colgroups, cellSelectionRangeData } = props

            if (colgroups.find(x => x.fixed === "left")) {
                const col = colgroups.find(x => !x.fixed)
                if (col && col.field === cellSelectionRangeData.leftColKey) {
                    result = true
                }
            }

            return result
        })

        const resetCellPositions = () => {
            // console.log(`resetCellPositions ing👇`)
            const { currentCell, normalEndCell } = props.cellSelectionData
            if (!isEmptyValue(currentCell.rowKey) && !isEmptyValue(currentCell.colKey)) {
                setSelectionPositions({ type: "currentCell" })
            }

            if (!isEmptyValue(normalEndCell.rowKey) && !isEmptyValue(normalEndCell.colKey)) {
                setSelectionPositions({ type: "normalEndCell" })
            }
        }

        const setCellEls = () => {
            if (props.isVirtualScroll && selectionBordersVisibility.value) {
                setCurrentCellEl()
                setNormalEndCellEl()
            }
        }

        const setCellSelectionRangeData = () => {
            const { currentCellSelectionType, cellSelectionData } = props
            const { currentCell, normalEndCell } = cellSelectionData

            let result = {}

            if (currentCellSelectionType === CURRENT_CELL_SELECTION_TYPES.SINGLE) {
                result = {
                    leftColKey: currentCell.colKey,
                    rightColKey: currentCell.colKey,
                    topRowKey: currentCell.rowKey,
                    bottomRowKey: currentCell.rowKey,
                }
            } else if (currentCellSelectionType === CURRENT_CELL_SELECTION_TYPES.RANGE) {
                const leftmostColKey = getLeftmostColKey({
                    colgroups: props.colgroups,
                    colKeys: [currentCell.colKey, normalEndCell.colKey],
                })

                /*
        current cell col key is leftmost colKey
        需要用 colKey 的位置进行判断，不能根据当前单元格 left 值判断（固定列时）
        */
                if (leftmostColKey === currentCell.colKey) {
                    result.leftColKey = currentCell.colKey
                    result.rightColKey = normalEndCell.colKey
                } else {
                    result.leftColKey = normalEndCell.colKey
                    result.rightColKey = currentCell.colKey
                }

                if (currentCell.rowIndex < normalEndCell.rowIndex) {
                    result.topRowKey = currentCell.rowKey
                    result.bottomRowKey = normalEndCell.rowKey
                } else {
                    result.topRowKey = normalEndCell.rowKey
                    result.bottomRowKey = currentCell.rowKey
                }
            } else {
                // clear
                result = {
                    leftColKey: "",
                    rightColKey: "",
                    topRowKey: "",
                    bottomRowKey: "",
                }
            }

            dispatch(EMIT_EVENTS.CELL_SELECTION_RANGE_DATA_CHANGE, result)
        }

        const getCellPosition = ({ cellEl, tableLeft, tableTop }) => {
            if (!selectionBordersVisibility.value) {
                return false
            }

            const {
                left: cellLeft,
                top: cellTop,
                height: cellHeight,
                width: cellWidth,
            } = cellEl.getBoundingClientRect()

            if (cellHeight && cellWidth) {
                return {
                    left: cellLeft - tableLeft,
                    top: cellTop - tableTop,
                    width: cellWidth,
                    height: cellHeight,
                }
            }
        }

        const getCellPositionByColKey = ({ tableLeft, tableTop, colKey, isFirstRow, isLastRow }) => {
            if (!selectionBordersVisibility.value) {
                return false
            }

            let cellEl
            if (isFirstRow) {
                cellEl = getTableFirstRowCellByColKey(colKey)
            } else if (isLastRow) {
                cellEl = getTableLastRowCellByColKey(colKey)
            }

            if (!cellEl) {
                return
            }

            const {
                left: cellLeft,
                top: cellTop,
                //height: cellHeight,
                width: cellWidth,
            } = cellEl.getBoundingClientRect()

            if (cellWidth) {
                return {
                    left: cellLeft - tableLeft,
                    top: cellTop - tableTop,
                    width: cellWidth,
                }
            }
        }

        const setSelectionPositions = ({ type }) => {
            const { allRowKeys, tableEl, cellSelectionData, virtualScrollVisibleIndexs } = props
            // console.log(`setSelectionPositions ing👇`)
            // table empty
            if (allRowKeys.length === 0) {
                return false
            }

            if (!tableEl) return false

            const { left: tableLeft, top: tableTop } = tableEl.getBoundingClientRect()

            let isCurrentCellOverflow = false
            let isNormalEndCellOverflow = false
            // set current cell position
            if (type === "currentCell") {
                isCurrentCellOverflow = true
                if (a.currentCellEl) {
                    const rect = getCellPosition({
                        cellEl: a.currentCellEl,
                        tableLeft,
                        tableTop,
                    })
                    if (rect) {
                        isCurrentCellOverflow = false
                        a.cellSelectionRect.currentCellRect = rect
                    }
                }
            }

            // set nromal end cell position`
            if (type === "normalEndCell") {
                isNormalEndCellOverflow = true
                if (a.normalEndCellEl) {
                    const rect = getCellPosition({
                        cellEl: a.normalEndCellEl,
                        tableLeft,
                        tableTop,
                    })
                    if (rect) {
                        isNormalEndCellOverflow = false
                        a.cellSelectionRect.normalEndCellRect = rect
                    }
                }
            }

            // current cell overflow or normal end cell overflow && is virtual scroll
            if ((isCurrentCellOverflow || isNormalEndCellOverflow) && props.isVirtualScroll) {
                const { currentCell, normalEndCell } = cellSelectionData
                // 弥补的
                let mackUpColKey
                let mackUpRowIndex

                if (isCurrentCellOverflow) {
                    mackUpColKey = currentCell.colKey
                    mackUpRowIndex = currentCell.rowIndex
                } else {
                    mackUpColKey = normalEndCell.colKey
                    mackUpRowIndex = normalEndCell.rowIndex
                }

                let mackUpRect
                /*
        当没有 currentCellRect 或 normalCellRect 时 进行纠正，否则只更新top值
        */
                if (
                    (isCurrentCellOverflow && !a.cellSelectionRect.currentCellRect.height) ||
                    (isNormalEndCellOverflow && !a.cellSelectionRect.normalEndCellRect.height)
                ) {
                    let mackUpRectParams = {
                        tableLeft,
                        tableTop,
                        colKey: mackUpColKey,
                    }
                    // 上方超出
                    if (mackUpRowIndex < virtualScrollVisibleIndexs.start) {
                        mackUpRect = getCellPositionByColKey({
                            ...mackUpRectParams,
                            isFirstRow: true,
                        })
                    }
                    // 下方超出
                    else if (mackUpRowIndex > virtualScrollVisibleIndexs.end) {
                        mackUpRect = getCellPositionByColKey({
                            ...mackUpRectParams,
                            isLastRow: true,
                        })
                    }
                }
                // 仅更新 top 值
                else {
                    // 上方超出
                    if (mackUpRowIndex < virtualScrollVisibleIndexs.start) {
                        mackUpRect = {
                            top: 0,
                        }
                    }
                    // 下方超出
                    else if (mackUpRowIndex > virtualScrollVisibleIndexs.end) {
                        mackUpRect = {
                            top: tableEl.clientHeight,
                        }
                    }
                }

                if (isCurrentCellOverflow) {
                    Object.assign(a.cellSelectionRect.currentCellRect, mackUpRect)
                } else {
                    Object.assign(a.cellSelectionRect.normalEndCellRect, mackUpRect)
                }
            }

            if (a.autoFillEndCellEl && type === "autoFillEndCell") {
                const rect = getCellPosition({
                    cellEl: a.autoFillEndCellEl,
                    tableLeft,
                    tableTop,
                })

                if (rect) {
                    a.cellSelectionRect.autoFillEndCellRect = rect
                }
            }
        }

        const 取当前选中 = ({ fixedType }) => {
            // console.log(`取当前选中 ing👇`)
            let result = {
                selectionCurrent: null,
                autoFillArea: null,
            }
            const { cellSelectionRect } = a
            const { colgroups, cellSelectionData } = props
            const { currentCellRect, normalEndCellRect } = cellSelectionRect
            if (!currentCellRect.width) {
                return result
            }

            const borders = {
                borderWidth: currentCellRect.width + 1,
                borderHeight: currentCellRect.height,
                topBorder: {
                    show: true,
                    width: 0,
                    height: 2,
                    top: currentCellRect.top - 1,
                    left: currentCellRect.left - 1,
                },
                rightBorder: {
                    show: true,
                    width: 2,
                    height: 0,
                    top: currentCellRect.top,
                    left: currentCellRect.left + currentCellRect.width - 2,
                },
                bottomBorder: {
                    show: true,
                    width: 0,
                    height: 2,
                    top: currentCellRect.top + currentCellRect.height - 2,
                    left: currentCellRect.left - 1,
                },
                leftBorder: {
                    show: true,
                    width: 2,
                    height: 0,
                    top: currentCellRect.top,
                    left: currentCellRect.left - 1,
                },
                corner: {
                    show: !normalEndCellRect.width,
                    top: 0,
                    left: 0,
                },
            }

            borders.corner.top = borders.bottomBorder.top - 3
            borders.corner.left = borders.rightBorder.left - 3

            // cell selection single autofill
            if (!normalEndCellRect.width) {
                result.autoFillArea = 成自动填充选中区域({
                    areaPostions: borders,
                    fixedType,
                })
            }

            const totalColKeys = [cellSelectionData.currentCell.colKey]

            const fixedColKeys = getColKeysByFixedTypeWithinColKeys({
                colKeys: totalColKeys,
                fixedType,
                colgroups,
            })

            // console.log(`加class名称 selection-current ing👇`)
            result.selectionCurrent = 成边框({
                ...borders,
                showCorner: !normalEndCellRect.width,
                类名: "selection-current",
                fixedType,
                totalColKeys,
                fixedColKeys,
            })

            return result
        }

        const 成选中区域 = ({ fixedType }) => {
            // console.log(`成选中区域 ing👇`)
            let result = {
                normalArea: null,
                autoFillArea: null,
            }

            const { cellSelectionRect } = a
            const { cellSelectionRangeData, colgroups, cellSelectionData } = props
            const { currentCell, normalEndCell } = cellSelectionData

            const { currentCellRect, normalEndCellRect } = cellSelectionRect

            if (!currentCellRect.width || !normalEndCellRect.width) {
                return result
            }

            const borders = {
                borderWidth: 0,
                borderHeight: 0,
                topBorder: {
                    show: true,
                    width: 0,
                    height: 1,
                    top: 0,
                    left: 0,
                },
                rightBorder: {
                    show: true,
                    width: 1,
                    height: 0,
                    top: 0,
                    left: 0,
                },
                bottomBorder: {
                    show: true,
                    width: 0,
                    height: 1,
                    top: 0,
                    left: 0,
                },
                leftBorder: {
                    show: true,
                    width: 1,
                    height: 0,
                    top: 0,
                    left: 0,
                },
                corner: {
                    show: true,
                    top: 0,
                    left: 0,
                },
            }

            const leftmostColKey = getLeftmostColKey({
                colgroups: colgroups,
                colKeys: [currentCell.colKey, normalEndCell.colKey],
            })

            // end cell column key right
            if (leftmostColKey === currentCell.colKey) {
                borders.borderWidth = normalEndCellRect.left - currentCellRect.left + normalEndCellRect.width + 1

                borders.topBorder.left = currentCellRect.left - 1
                borders.bottomBorder.left = currentCellRect.left - 1
                borders.leftBorder.left = currentCellRect.left - 1
                borders.rightBorder.left = normalEndCellRect.left + normalEndCellRect.width - 1
            }
            // end cell column key left or equal
            else if (leftmostColKey === normalEndCell.colKey) {
                borders.borderWidth = currentCellRect.left - normalEndCellRect.left + currentCellRect.width + 1

                borders.topBorder.left = normalEndCellRect.left - 1
                borders.rightBorder.left = currentCellRect.left + currentCellRect.width - 1
                borders.bottomBorder.left = normalEndCellRect.left - 1
                borders.leftBorder.left = normalEndCellRect.left - 1
            }

            // end cell below
            if (normalEndCellRect.top > currentCellRect.top) {
                borders.borderHeight = normalEndCellRect.top - currentCellRect.top + normalEndCellRect.height

                borders.topBorder.top = currentCellRect.top - 1
                borders.rightBorder.top = currentCellRect.top
                borders.bottomBorder.top = normalEndCellRect.top + normalEndCellRect.height - 1
                borders.leftBorder.top = currentCellRect.top
            }
            // end cell above or equal
            else if (normalEndCellRect.top <= currentCellRect.top) {
                borders.borderHeight = currentCellRect.top - normalEndCellRect.top + currentCellRect.height

                borders.topBorder.top = normalEndCellRect.top - 1
                borders.rightBorder.top = normalEndCellRect.top
                borders.bottomBorder.top = currentCellRect.top + currentCellRect.height - 1
                borders.leftBorder.top = normalEndCellRect.top
            }

            borders.corner.top = borders.bottomBorder.top - 4
            borders.corner.left = borders.rightBorder.left - 4

            if (normalEndCellRect.width) {
                result.autoFillArea = 成自动填充选中区域({
                    areaPostions: borders,
                    fixedType,
                })
            }

            const { leftColKey, rightColKey } = cellSelectionRangeData
            console.log(`cellSelectionRangeData 👉`,cellSelectionRangeData)
            const totalColKeys = getColKeysByRangeColKeys({
                colKey1: leftColKey,
                colKey2: rightColKey,
                colgroups,
            })

            const fixedColKeys = getColKeysByFixedTypeWithinColKeys({
                colKeys: totalColKeys,
                fixedType,
                colgroups,
            })

            result.normalArea = 成边框({
                ...borders,
                类名: "selection-normal-area",
                fixedType,
                totalColKeys,
                fixedColKeys,
            })

            result.normalAreaLayer = getAreaLayer({
                ...borders,
                类名: "selection-normal-area-layer",
                fixedType,
                totalColKeys,
                fixedColKeys,
            })

            return result
        }

        const 成自动填充选中区域 = ({ areaPostions, fixedType }) => {
            let result = null
            const { cellSelectionRect } = a
            const {
                cellAutofillOption,
                cellSelectionRangeData,
                cellSelectionData,
                isAutofillStarting,
                currentCellSelectionType,
                colgroups,
            } = props

            if (!isAutofillStarting) return result
            const { currentCellRect, autoFillEndCellRect } = cellSelectionRect
            if (!currentCellRect.width || !autoFillEndCellRect.width) {
                return result
            }

            if (!areaPostions) {
                return result
            }

            const borders = {
                borderWidth: 0,
                borderHeight: 0,
                topBorder: {
                    show: true,
                    width: 0,
                    height: 1,
                    top: 0,
                    left: 0,
                },
                rightBorder: {
                    show: true,
                    width: 1,
                    height: 0,
                    top: 0,
                    left: 0,
                },
                bottomBorder: {
                    show: true,
                    width: 0,
                    height: 1,
                    top: 0,
                    left: 0,
                },
                leftBorder: {
                    show: true,
                    width: 1,
                    height: 0,
                    top: 0,
                    left: 0,
                },
                corner: {
                    show: false,
                    top: 0,
                    left: 0,
                },
            }

            const { currentCell, autoFillEndCell } = cellSelectionData

            let { leftColKey, rightColKey } = cellSelectionRangeData
            if (currentCellSelectionType === CURRENT_CELL_SELECTION_TYPES.SINGLE) {
                leftColKey = currentCell.colKey
                rightColKey = currentCell.colKey
            }

            let leftmostColKey
            if (leftColKey !== autoFillEndCell.colKey) {
                leftmostColKey = getLeftmostColKey({
                    colgroups,
                    colKeys: [leftColKey, autoFillEndCell.colKey],
                })
            }

            let rightmostColKey
            if (rightColKey !== autoFillEndCell.colKey) {
                rightmostColKey = getRightmostColKey({
                    colgroups,
                    colKeys: [rightColKey, autoFillEndCell.colKey],
                })
            }

            // autofilling direction
            let autofillingDirection

            let rangeColKey1
            let rangeColKey2

            // auto fill end cell below
            if (autoFillEndCellRect.top > areaPostions.bottomBorder.top) {
                autofillingDirection = AUTOFILLING_DIRECTION.DOWN

                rangeColKey1 = leftColKey
                rangeColKey2 = rightColKey

                borders.topBorder.show = false

                borders.borderWidth = areaPostions.borderWidth
                borders.borderHeight =
                    autoFillEndCellRect.top - areaPostions.bottomBorder.top + autoFillEndCellRect.height

                borders.rightBorder.top = areaPostions.bottomBorder.top
                borders.rightBorder.left = areaPostions.rightBorder.left
                if (currentCellSelectionType === CURRENT_CELL_SELECTION_TYPES.SINGLE) {
                    borders.rightBorder.left++
                }

                borders.leftBorder.top = areaPostions.bottomBorder.top
                borders.leftBorder.left = areaPostions.leftBorder.left

                borders.bottomBorder.top = autoFillEndCellRect.top + autoFillEndCellRect.height - 1
                borders.bottomBorder.left = areaPostions.bottomBorder.left
            }
            // end cell above
            else if (autoFillEndCellRect.top < areaPostions.topBorder.top) {
                autofillingDirection = AUTOFILLING_DIRECTION.UP

                rangeColKey1 = leftColKey
                rangeColKey2 = rightColKey

                borders.bottomBorder.show = false

                borders.borderWidth = areaPostions.borderWidth
                borders.borderHeight = areaPostions.topBorder.top - autoFillEndCellRect.top

                borders.topBorder.top = autoFillEndCellRect.top - 1
                borders.topBorder.left = areaPostions.topBorder.left

                borders.rightBorder.top = autoFillEndCellRect.top
                borders.rightBorder.left = areaPostions.rightBorder.left
                if (currentCellSelectionType === CURRENT_CELL_SELECTION_TYPES.SINGLE) {
                    borders.rightBorder.left++
                }

                borders.leftBorder.top = autoFillEndCellRect.top
                borders.leftBorder.left = areaPostions.leftBorder.left
            }
            // auto fill end cell right
            else if (rightmostColKey === autoFillEndCell.colKey && !isEmptyValue(rightmostColKey)) {
                autofillingDirection = AUTOFILLING_DIRECTION.RIGHT

                rangeColKey1 = getNextColKey({
                    colgroups,
                    currentColKey: rightColKey,
                })
                rangeColKey2 = autoFillEndCell.colKey

                borders.leftBorder.show = false

                borders.borderWidth =
                    autoFillEndCellRect.left - areaPostions.rightBorder.left + autoFillEndCellRect.width + 1
                borders.borderHeight = areaPostions.borderHeight

                borders.topBorder.top = areaPostions.topBorder.top
                borders.topBorder.left = areaPostions.rightBorder.left - 1

                borders.rightBorder.top = areaPostions.topBorder.top
                borders.rightBorder.left = autoFillEndCellRect.left + autoFillEndCellRect.width - 1

                borders.bottomBorder.top = areaPostions.bottomBorder.top
                borders.bottomBorder.left = areaPostions.rightBorder.left - 1
            }
            // auto fill end cell left
            else if (leftmostColKey === autoFillEndCell.colKey && !isEmptyValue(leftmostColKey)) {
                autofillingDirection = AUTOFILLING_DIRECTION.LEFT

                rangeColKey1 = getPreviewColKey({
                    colgroups,
                    currentColKey: leftColKey,
                })
                rangeColKey2 = autoFillEndCell.colKey

                borders.rightBorder.show = false

                borders.borderWidth = areaPostions.leftBorder.left - autoFillEndCellRect.left + 1
                borders.borderHeight = areaPostions.borderHeight

                borders.topBorder.top = areaPostions.topBorder.top
                borders.topBorder.left = autoFillEndCellRect.left

                borders.rightBorder.left = areaPostions.topBorder.left

                borders.bottomBorder.top = areaPostions.bottomBorder.top
                borders.bottomBorder.left = autoFillEndCellRect.left

                borders.leftBorder.top = areaPostions.topBorder.top
                borders.leftBorder.left = autoFillEndCellRect.left
            } else {
                return result
            }

            const { directionX, directionY } = cellAutofillOption
            if (isBoolean(directionX) && !directionX) {
                if (
                    autofillingDirection === AUTOFILLING_DIRECTION.LEFT ||
                    autofillingDirection === AUTOFILLING_DIRECTION.RIGHT
                ) {
                    return false
                }
            }

            if (isBoolean(directionY) && !directionY) {
                if (
                    autofillingDirection === AUTOFILLING_DIRECTION.UP ||
                    autofillingDirection === AUTOFILLING_DIRECTION.DOWN
                ) {
                    return false
                }
            }

            const totalColKeys = getColKeysByRangeColKeys({
                colKey1: rangeColKey1,
                colKey2: rangeColKey2,
                colgroups,
            })

            let fixedColKeys = getColKeysByFixedTypeWithinColKeys({
                colKeys: totalColKeys,
                fixedType,
                colgroups,
            })

            result = 成边框({
                类名: "selection-autofill-area",
                ...borders,
                fixedType,
                totalColKeys,
                fixedColKeys,
            })

            if (result) {
                dispatch(EMIT_EVENTS.AUTOFILLING_DIRECTION_CHANGE, autofillingDirection)
            }

            return result
        }

        function 成边框({
            borderWidth,
            borderHeight,
            topBorder,
            rightBorder,
            bottomBorder,
            leftBorder,
            corner,
            类名,
            fixedType,
            totalColKeys,
            fixedColKeys,
        }) {
            const { colgroups } = props
            // console.log(`成边框 ing👇`)
            let isRender = true

            if (fixedType) {
                isRender = isExistGivenFixedColKey({
                    fixedType,
                    colKeys: totalColKeys,
                    colgroups,
                })
            } else {
                isRender = isExistNotFixedColKey({
                    colKeys: totalColKeys,
                    colgroups,
                })
            }

            if (!isRender) {
                return null
            }

            let fixedColsTotalWidth = 0
            if (fixedColKeys.length) {
                fixedColsTotalWidth = getTotalWidthByColKeys({
                    colKeys: fixedColKeys,
                    colgroups,
                })
            }

            if (fixedType) {
                borderWidth = fixedColsTotalWidth
                if (fixedType === COLUMN_FIXED_TYPE.LEFT) {
                    borderWidth += 1
                }
            }

            if (fixedType === COLUMN_FIXED_TYPE.LEFT) {
                if (totalColKeys.length !== fixedColKeys.length) {
                    rightBorder.show = false
                    corner.show = false
                }
            }

            if (fixedType === COLUMN_FIXED_TYPE.RIGHT) {
                if (totalColKeys.length !== fixedColKeys.length) {
                    leftBorder.show = false
                }

                topBorder.left = rightBorder.left - borderWidth + 1
                bottomBorder.left = rightBorder.left - borderWidth + 1
            }

            if (isFirstSelectionRow.value) {
                topBorder.top += 1
            }
            if (isFirstSelectionCol.value) {
                leftBorder.left += 1
            }
            if (isFirstNotFixedSelectionCol.value) {
                leftBorder.left += 1
            }

            let cornerTop = corner.top
            let cornerLeft = corner.left
            let cornerBorderRightWidth = "1px"
            let cornerBorderBottomtWidth = "1px"

            if (cornerCellInfo.value.isLastRow) {
                cornerTop -= 3
                cornerBorderBottomtWidth = "0px"
            }

            if (cornerCellInfo.value.isLastColumn) {
                cornerLeft -= 3
                cornerBorderRightWidth = "0px"
            }

            if (!showCorner.value) {
                corner.show = false
            }

            const cornerProps = {
                class: 拼样式名_table直属("selection-corner"),
                style: {
                    display: corner.show ? "block" : "none",
                    top: cornerTop + "px",
                    left: cornerLeft + "px",
                    borderWidth: `1px ${cornerBorderRightWidth} ${cornerBorderBottomtWidth} 1px`,
                },
                onMousedown: e => {
                    dispatch(EMIT_EVENTS.SELECTION_CORNER_MOUSEDOWN, {
                        event: e,
                    })
                },
                onMouseup: e => {
                    dispatch(EMIT_EVENTS.SELECTION_CORNER_MOUSEUP, {
                        event: e,
                    })
                },
            }
            // console.log(`类名 👉`,类名)
            return (
                <div class={拼样式名_table直属(类名)}>
                    {/* top */}
                    <div
                        style={{
                            display: topBorder.show ? "block" : "none",
                            width: borderWidth + "px",
                            height: topBorder.height + "px",
                            top: topBorder.top + "px",
                            left: topBorder.left + "px",
                        }}
                        class={拼样式名_table直属("selection-border")}
                    />
                    {/* right */}
                    <div
                        style={{
                            display: rightBorder.show ? "block" : "none",
                            width: rightBorder.width + "px",
                            height: borderHeight + "px",
                            top: rightBorder.top + "px",
                            left: rightBorder.left + "px",
                        }}
                        class={拼样式名_table直属("selection-border")}
                    />
                    {/* bottom */}
                    <div
                        style={{
                            display: bottomBorder.show ? "block" : "none",
                            width: borderWidth + "px",
                            height: bottomBorder.height + "px",
                            top: bottomBorder.top + "px",
                            left: bottomBorder.left + "px",
                        }}
                        class={拼样式名_table直属("selection-border")}
                    />
                    <div
                        style={{
                            display: leftBorder.show ? "block" : "none",
                            width: leftBorder.width + "px",
                            height: borderHeight + "px",
                            top: leftBorder.top + "px",
                            left: leftBorder.left + "px",
                        }}
                        class={拼样式名_table直属("selection-border")}
                    />
                    {corner.show && <div {...cornerProps} />}
                </div>
            )
        }

        function getAreaLayer({ borderWidth, borderHeight, topBorder, 类名, fixedType, totalColKeys, fixedColKeys }) {
            console.log(`getAreaLayer ing👇`)
            const { colgroups } = props
            let isRender = true
            if (fixedType) {
                isRender = isExistGivenFixedColKey({
                    fixedType,
                    colKeys: totalColKeys,
                    colgroups,
                })
            } else {
                isRender = isExistNotFixedColKey({
                    colKeys: totalColKeys,
                    colgroups,
                })
            }
            if (!isRender) return null

            let fixedColsTotalWidth = 0
            if (fixedColKeys.length) {
                fixedColsTotalWidth = getTotalWidthByColKeys({
                    colKeys: fixedColKeys,
                    colgroups,
                })
            }

            if (fixedType) {
                borderWidth = fixedColsTotalWidth
                if (fixedType === COLUMN_FIXED_TYPE.LEFT) {
                    borderWidth += 1
                }
            }

            return (
                <div
                    class={拼样式名_table直属(类名)}
                    style={{
                        top: topBorder.top + "px",
                        left: topBorder.left + "px",
                        width: borderWidth + "px",
                        height: borderHeight + "px",
                    }}
                />
            )
        }

        function getTableFirstRowCellByColKey(colKey) {
            const { tableEl } = props
            let result = null

            if (tableEl) {
                result = tableEl.querySelector(`tbody.ve-table-body tr td[col-key="${colKey}"]`)
            }
            return result
        }

        function getTableLastRowCellByColKey(colKey) {
            const { tableEl } = props
            let result = null

            if (tableEl) {
                result = tableEl.querySelector(`tbody.ve-table-body tr:last-child td[col-key="${colKey}"]`)
            }
            return result
        }

        function getTableCellEl({ rowKey, colKey }) {
            const { tableEl } = props
            let result = null

            if (tableEl) {
                result = tableEl.querySelector(`tbody.ve-table-body tr[row-key="${rowKey}"] td[col-key="${colKey}"]`)
            }
            return result
        }

        function setCurrentCellEl() {
            // console.log(`setCurrentCellEl 👉`,setCurrentCellEl)
            const { cellSelectionData } = props
            const { rowKey, colKey } = cellSelectionData.currentCell
            if (!isEmptyValue(rowKey) && !isEmptyValue(colKey)) {
                const cellEl = getTableCellEl({ rowKey, colKey })
                if (cellEl) {
                    a.currentCellEl = cellEl
                }
            }
        }

        function setNormalEndCellEl() {
            const { cellSelectionData } = props
            const { rowKey, colKey } = cellSelectionData.normalEndCell
            if (!isEmptyValue(rowKey) && !isEmptyValue(colKey)) {
                const cellEl = getTableCellEl({ rowKey, colKey })
                if (cellEl) {
                    a.normalEndCellEl = cellEl
                }
            }
        }

        function setAutofillEndCellEl() {
            const { cellSelectionData, tableEl } = props
            const { rowKey, colKey } = cellSelectionData.autoFillEndCell
            if (tableEl) {
                const autoFillEndCellEl = tableEl.querySelector(
                    `tbody.ve-table-body tr[row-key="${rowKey}"] td[col-key="${colKey}"]`
                )
                if (autoFillEndCellEl) {
                    a.autoFillEndCellEl = autoFillEndCellEl
                }
            }
        }

        function clearAutofillEndCellRect() {
            a.autoFillEndCellEl = null
            a.cellSelectionRect.autoFillEndCellRect = {
                left: 0,
                top: 0,
                width: 0,
                height: 0,
            }
        }

        function clearCurrentCellRect() {
            a.currentCellEl = null
            a.cellSelectionRect.currentCellRect = {
                left: 0,
                top: 0,
                width: 0,
                height: 0,
            }
        }

        function clearNormalEndCellRect() {
            a.normalEndCellEl = null
            a.cellSelectionRect.normalEndCellRect = {
                left: 0,
                top: 0,
                width: 0,
                height: 0,
            }
        }

        onMounted(() => {
            a.debounceResetCellPositions = useDebounceFn(resetCellPositions, 210)
            a.debounceSetCellEls = useDebounceFn(setCellEls, 200)
        })

        const fixedLeftSelectionCurrent = computed(() => 取当前选中({ fixedType: COLUMN_FIXED_TYPE.LEFT }))

        const fixedLeftSelectionArea = computed(() => 成选中区域({ fixedType: COLUMN_FIXED_TYPE.LEFT }))

        const fixedLeftAutoFillArea = computed(
            () => fixedLeftSelectionCurrent.value.autoFillArea || fixedLeftSelectionArea.value.autoFillArea
        )

        const middleSelectionCurrent = computed(() => 取当前选中({ fixedType: "" }))

        const middleSelectionArea = computed(() => 成选中区域({ fixedType: "" }))

        const middleAutoFillArea = computed(
            () => middleSelectionCurrent.value.autoFillArea || middleSelectionArea.value.autoFillArea
        )

        const fixedRightSelectionCurrent = computed(() => 取当前选中({ fixedType: COLUMN_FIXED_TYPE.RIGHT }))

        const fixedRightSelectionArea = computed(() => 成选中区域({ fixedType: COLUMN_FIXED_TYPE.RIGHT }))

        const fixedRightAutoFillArea = computed(
            () => fixedRightSelectionCurrent.value.autoFillArea || fixedRightSelectionArea.value.autoFillArea
        )

        watch(
            () => props.parentRendered,
            val => {
                // console.log(`selection props.parentRendered变化了 👉`, val)
                if (val) {
                    // add table container scroll hook
                    props.hooks.addHook(HOOKS_NAME.TABLE_CONTAINER_SCROLL, () => {
                        // Assuming setCellEls and debounceSetCellEls are functions defined elsewhere
                        setCellEls()
                        debounceSetCellEls()
                        resetCellPositions()
                        // debounceResetCellPositions()
                    })
                    // add table size change hook
                    props.hooks.addHook(HOOKS_NAME.TABLE_SIZE_CHANGE, () => {
                        // debounceResetCellPositions()
                    })
                    // add table td width change hook
                    props.hooks.addHook(HOOKS_NAME.TABLE_CELL_WIDTH_CHANGE, () => {
                        nextTick(() => {
                            resetCellPositions()
                        })
                    })
                    // add clipboard cell value change hook
                    props.hooks.addHook(HOOKS_NAME.CLIPBOARD_CELL_VALUE_CHANGE, () => {
                        nextTick(() => {
                            resetCellPositions()
                        })
                    })
                }
            },
            { immediate: true }
        )

        // watchEffect(
        //   (val) => {
        //     console.log(
        //       `props.cellSelectionData.currentCell 👉`,
        //       props.cellSelectionData.currentCell
        //     )
        //     const { rowKey, colKey } = val
        //     if (!isEmptyValue(rowKey) && !isEmptyValue(colKey)) {
        //       setCurrentCellEl()
        //       setSelectionPositions({ type: 'currentCell' })
        //     } else {
        //       // Assuming INSTANCE_METHODS.CLEAR_CURRENT_CELL_RECT is a function defined elsewhere
        //       // CLEAR_CURRENT_CELL_RECT()
        //     }
        //     setCellSelectionRangeData()
        //   }
        // )
        watch(
            () => props.cellSelectionData.currentCell,
            val => {
                // console.log(
                //   `props.cellSelectionData.currentCell 👉`,
                //   props.cellSelectionData.currentCell
                // )
                const { rowKey, colKey } = val
                if (!isEmptyValue(rowKey) && !isEmptyValue(colKey)) {
                    setCurrentCellEl()
                    setSelectionPositions({ type: "currentCell" })
                } else {
                    // Assuming INSTANCE_METHODS.CLEAR_CURRENT_CELL_RECT is a function defined elsewhere
                    // CLEAR_CURRENT_CELL_RECT()
                }
                setCellSelectionRangeData()
            },
            { immediate: true, deep: true }
        )

        watch(
            () => props.cellSelectionData.normalEndCell,
            val => {
                console.log(`normalEndCell 改变 ing👇`)
                const { rowKey, colKey } = val
                if (!isEmptyValue(rowKey) && !isEmptyValue(colKey)) {
                    setNormalEndCellEl()
                    setSelectionPositions({ type: "normalEndCell" })
                } else {
                    // Assuming INSTANCE_METHODS.CLEAR_NORMAL_END_CELL_RECT is a function defined elsewhere
                    // CLEAR_NORMAL_END_CELL_RECT()
                }
                setCellSelectionRangeData()
            },
            { immediate: true, deep: true }
        )

        watch(
            () => props.cellSelectionData.autoFillEndCell,
            val => {
                const { rowKey, colKey } = val
                if (!isEmptyValue(rowKey) && !isEmptyValue(colKey)) {
                    setAutofillEndCellEl()
                    setSelectionPositions({ type: "autoFillEndCell" })
                } else {
                    clearAutofillEndCellRect()
                }
            },
            { immediate: true, deep: true }
        )

        return () => {
            if (!selectionBordersVisibility.value) {
                return null
            }

            return (
                <div
                    class={拼样式名_table直属("selection-wrapper")}
                    style={{ visibility: props.isCellEditing ? "hidden" : "" }}>
                    <span>props.isCellEditing{props.isCellEditing}</span>
                    <div class={拼样式名_table直属("selection-fixed-left")}>
                        {/* current */}
                        {fixedLeftSelectionCurrent.value.selectionCurrent}
                        {/* area */}
                        {fixedLeftSelectionArea.value.normalArea}
                        {/* auto fill */}
                        {fixedLeftAutoFillArea.value}
                        {/* area layer */}
                        {fixedLeftSelectionArea.value.normalAreaLayer}
                    </div>
                    <div class={拼样式名_table直属("selection-middle")}>
                        {/* current */}
                        {middleSelectionCurrent.value.selectionCurrent}
                        {/* area */}
                        {middleSelectionArea.value.normalArea}
                        {/* auto fill */}
                        {middleAutoFillArea.value}
                        {/* area layer */}
                        {middleSelectionArea.value.normalAreaLayer}
                    </div>
                    <div class={拼样式名_table直属("selection-fixed-right")}>
                        {/* current */}
                        {fixedRightSelectionCurrent.value.selectionCurrent}
                        {/* area */}
                        {fixedRightSelectionArea.value.normalArea}
                        {/* auto fill */}
                        {fixedRightAutoFillArea.value}
                        {/* area layer */}
                        {fixedRightSelectionArea.value.normalAreaLayer}
                    </div>
                </div>
            )
        }
    },
})
